package org.example.jwtdemo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.example.jwtdemo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class jwtutils {


    private static final String SECRET = "secret";
    /**
     * 生成token header.payload.signature
     */
    public static String geteToken(Map<String, String> map){
        Date date = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24);
//        map.put("id","1");
//        map.put("username","admin");

        //创建jwt
        JWTCreator.Builder builder = JWT.create();

        //payload
        map.forEach((key,value)->{
            builder.withClaim(key,value); //添加payload
        });

        //指定过期时间
        String token = builder.withExpiresAt(date)//设置过期时间
                .sign(Algorithm.HMAC256(SECRET));//设置签名


        return token;
    }

    /**
     * 验证token 合法性
     */
    public static DecodedJWT verifyToken(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();//创建验证对象
        DecodedJWT decodedJWT = jwtVerifier.verify(token);//验证jwt令牌
        return decodedJWT; //验证通过
    }

    /**
     * 获取token中的信息
     */
//    public static DecodedJWT getTokenInfo(String token) {//也可以不需要
//        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);//创建验证对象
//        return  jwt;
//    };
}
